package com.restaurant.springboot.controller;

import com.restaurant.springboot.annotation.MayHaveBug;
import com.restaurant.springboot.annotation.TokenAuth;
import com.restaurant.springboot.entity.UserEntity;
import com.restaurant.springboot.entity.dto.CommentDTO;
import com.restaurant.springboot.service.CommentService;
import com.restaurant.springboot.service.OrderService;
import com.restaurant.springboot.service.UserService;
import com.restaurant.springboot.utils.RespCode;
import com.restaurant.springboot.utils.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("api/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;


    @GetMapping("{commentId}")
    public RespEntity getComment(@PathVariable(name = "commentId") int id) {
        return new RespEntity(RespCode.SUCCESS, commentService.getCommentById(id));
    }

    @GetMapping("{pageNum}/{pageSize}")
    public RespEntity getComments(@PathVariable int pageNum,@PathVariable int pageSize) {
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        return new RespEntity(RespCode.SUCCESS, commentService.findAll(pageable)) ;
    }

    /**
     * 添加评论
     * @param comment
     * @return
     */
    @PostMapping("")
    @MayHaveBug("无法传递用户userId")
    @TokenAuth
    public RespEntity insertComment(@RequestBody CommentDTO comment, HttpSession httpSession) {
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("user");
        comment.setUserId(userEntity.getId());
        if(orderService.isExistsOrder(comment.getOrderId())){
            if(commentService.isExistsComment(comment.getOrderId())){
                return new RespEntity(RespCode.ERROR,"comment is exists,do not comment again");
            }
            if(commentService.insertComment(comment)){
                return new RespEntity(RespCode.SUCCESS,"add comment success");
            }else{
                return new RespEntity(RespCode.ERROR,"add comment error");
            }
        }
        return new RespEntity(RespCode.ERROR,"order is not exists");
    }


    /**
     * 点赞
     * 可以无限点赞
     * @param commentId
     */
    @PutMapping("praise/{commentId}")
    public RespEntity praise(@PathVariable int commentId) {
        commentService.praise(commentId);
        return new RespEntity(RespCode.SUCCESS,"点赞成功");
    }

}
